package com.itheima.web.controller.cargo;

import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import com.itheima.domain.cargo.ContractProduct;
import com.itheima.domain.cargo.ContractProductExample;
import com.itheima.domain.cargo.Factory;
import com.itheima.domain.cargo.FactoryExample;
import com.itheima.service.cargo.ContractProductService;
import com.itheima.service.cargo.FactoryService;
import com.itheima.utils.FileUploadUtil;
import com.itheima.web.controller.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/cargo/contractProduct")
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;

    @Reference
    private FactoryService factoryService;

    @Autowired
    private FileUploadUtil fileUploadUtil;

    @RequestMapping(value = "/list", name = "货物列表查询")
    public String list(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String contractId) {

        //1 查询当前合同下的所有货物信息
        ContractProductExample contractProductExample = new ContractProductExample();
        contractProductExample.createCriteria().andContractIdEqualTo(contractId);
        PageInfo pageInfo = contractProductService.findByPage(pageNum, pageSize, contractProductExample);
        request.setAttribute("page", pageInfo);

        //2 查询出所有生产货物的厂家列表
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        //3 回显合同ID
        request.setAttribute("contractId", contractId);

        //4 页面转发
        return "cargo/product/product-list";
    }


    @RequestMapping(value = "/toUpdate", name = "跳转货物修改页面")
    public String toUpdate(String id) {
        //1 查询当前货物信息
        ContractProduct contractProduct = contractProductService.findById(id);
        request.setAttribute("contractProduct", contractProduct);

        //2 查询出所有生产货物的厂家列表
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        request.setAttribute("factoryList", factoryList);

        return "cargo/product/product-update";
    }

    @RequestMapping(value = "/edit", name = "货物新增或修改")
    public String edit(ContractProduct contractProduct, MultipartFile productPhoto) {


        //1 调用工具类,实现文件上传
        try {
            String imagePath = fileUploadUtil.upload(productPhoto);
            contractProduct.setProductImage(imagePath);
        } catch (Exception e) {
            e.printStackTrace();
        }


        if (StringUtils.isEmpty(contractProduct.getId())) {
            contractProduct.setId(UUID.randomUUID().toString());

            //设置公司信息
            contractProduct.setCompanyId(getCompanyId());
            contractProduct.setCompanyName(getCompanyName());

            contractProductService.save(contractProduct);
        } else {
            contractProductService.update(contractProduct);
        }
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractProduct.getContractId();
    }

    @RequestMapping(value = "/delete", name = "货物删除")
    public String delete(String id, String contractId) {
        contractProductService.delete(id);//货物id
        return "redirect:/cargo/contractProduct/list.do?contractId=" + contractId;
    }


    @RequestMapping(value = "/toImport", name = "跳转货物批量上传页面")
    public String toImport(String contractId) {
        //回显合同ID
        request.setAttribute("contractId", contractId);

        return "cargo/product/product-import";
    }


    @RequestMapping(value = "/import", name = "货物批量上传功能")
    public String imports(String contractId, MultipartFile file) throws IOException {
        //1 解析这个文件----->List<ContractProduct>
        //1-1) 读取文件,获取到WorkBook
        Workbook workbook = new XSSFWorkbook(file.getInputStream());

        //1-2) 获取到Sheet
        Sheet sheet = workbook.getSheetAt(0);

        //1-3) 遍历读取行
        List<ContractProduct> list = new ArrayList<>();
        for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
            Row row = sheet.getRow(i);//一行

            Object[] objs = new Object[9];
            //1-4) 遍历读取单元格
            for (int j = 1; j < row.getLastCellNum(); j++) {
                //1-5) 获取单元格中的值,赋值到对象的属性上
                Cell cell = row.getCell(j);//1单元格
                objs[j - 1] = getCellValue(cell);
            }
            ContractProduct contractProduct = new ContractProduct(objs);

            //2 属性的补全
            contractProduct.setContractId(contractId);//合同ID
            contractProduct.setId(UUID.randomUUID().toString());//ID
            contractProduct.setCompanyId(getCompanyId());//企业ID
            contractProduct.setCompanyName(getCompanyName());//企业名称

            //设置工厂ID
            FactoryExample factoryExample = new FactoryExample();
            factoryExample.createCriteria().andFactoryNameEqualTo(contractProduct.getFactoryName());
            List<Factory> factories = factoryService.findAll(factoryExample);
            Factory factory = factories.get(0);
            contractProduct.setFactoryId(factory.getId());

            list.add(contractProduct);
        }
        System.out.println(list);

        //3 执行批量保存方法
        contractProductService.patchSave(list);

        return "redirect:/cargo/contract/list.do";
    }


    //解析每个单元格的数据
    public static Object getCellValue(Cell cell) {
        Object obj = null;
        CellType cellType = cell.getCellType(); //获取单元格数据类型
        switch (cellType) {
            case STRING: {
                obj = cell.getStringCellValue();//字符串
                break;
            }
            //excel默认将日期也理解为数字
            case NUMERIC: {
                if (DateUtil.isCellDateFormatted(cell)) {
                    obj = cell.getDateCellValue();//日期
                } else {
                    obj = cell.getNumericCellValue(); // 数字
                }
                break;
            }
            case BOOLEAN: {
                obj = cell.getBooleanCellValue(); // 布尔
                break;
            }
            default: {
                break;
            }
        }
        return obj;
    }
}
